package com.dy.数组.高级.螺旋矩阵2;

/*
给定一个正整数 n，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:
输入: 3
输出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
 */
public class Solution {
    public int[][] generateMatrix(int n) {
        int res[][] = new int[n][n];

        int c = 1, j = 0;

        while (c <= n * n) {
            if(j==n/2){
                res[j][j]=c++;
            }
            for (int i = j; i < n -1- j; i++) {
                res[j][i] = c++;
            }
            for (int i = j;i<n-1-j;i++){
                res[i][n-1-j] =c++;
            }
            for (int i = n-1-j;i>j;i--){
                res[n-1-j][i] =c++;
            }
            for (int i = n-1-j;i>j;i--){
                res[i][j] =c++;
            }
            j++;
            //print(res);
        }
        return res;

    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        solution.generateMatrix(5);
    }
    void print(int[][] a){
        for(int i=0;i<a.length;i++){
            for(int j=0;j<a.length;j++){
                System.out.print(a[i][j]+"  ");
            }
            System.out.println();
        }
        System.out.println();
    }
}
